package org.dongchao.statistics.exe;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.dongchao.statistics.pojo.RequestResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * job execute
 * @author dongyazhuo
 */
@Component
public class Execute {

	@Autowired
	RestTemplate restTemplate;

	@Value("${config.startTime}")
	String startTime;

	@Value("${config.endTime}")
	String endTime;

	@Value("${config.userList}")
	String userList;

	@Value("${config.requestUrl}")
	String requestUrl;

	@Value("${config.exeFinishShutdown}")
	boolean exeFinishShutdown;

	/**
	 * fileOutPutRequestResultHandller//文件输出
	 */
	/**
	 * emailRequestResultHandller //邮件推送
	 */
	/**
	 * printRequestResultHandller //屏幕打印
	 */
	@Resource(name = "requestResultHandller")
	RequestResultHandler requestResultHandler;

	public void execute() {

		List<String> emailList = getEmailList();
		List<RequestResult> collect = emailList.parallelStream().map(email -> request(startTime, endTime, email))
				.collect(Collectors.toList());
		requestResultHandler.handler(collect);
		if (exeFinishShutdown) {
			System.exit(0);
		}
	}

	/**
	 * 获取用户列表
	 * @return
	 */
	private List<String> getEmailList() {
		if (StringUtils.isNotBlank(userList)) {
			String[] split = userList.split(",");
			return Stream.of(split).map(name -> name + "@58.com").collect(Collectors.toList());
		}
		return Collections.emptyList();
	}

	private RequestResult request(String startTime, String endTime, String email) {
		String url = requestUrl + "/?start=" + startTime + "&end=" + endTime + "&email=" + email;
		ResponseEntity<RequestResult> entity = restTemplate.getForEntity(url, RequestResult.class);
		if (entity.getStatusCode().equals(HttpStatus.OK)) {
			return entity.getBody();
		}
		return null;
	}
}
